package com.cly.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.cly.config.AliProperties;
import com.cly.domain.Order;
import com.cly.feign.PayOrderFeign;
import com.cly.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private AlipayTradeService alipayTradeService;

    @Autowired
    private PayOrderFeign payOrderFeign;

    @Autowired
    private AliProperties aliProperties;


    /**
     * 创建支付二维码
     *
     * @param map
     * @return
     */
    @Override
    public String createPrePay(Map<String, String> map) {
        //根据一些条件创建 金额 名称
        String orderNumber = map.get("orderNumber");
        //远程调用order-service
        Order order = payOrderFeign.getOrderByNum(orderNumber);
        if (ObjectUtils.isEmpty(order)){
            throw new RuntimeException("根据订单号远程调用订单失败");
        }
        //获取大信息后
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder();
        //组装信息
        builder.setOutTradeNo(orderNumber)
                .setSubject(order.getProdName())
                .setTotalAmount(order.getActualTotal().toString())
                .setStoreId("test_store_id")
                .setSellerId("")
                .setOperatorId("test_operator_id")
                .setNotifyUrl("http://chengliaoyuan.cn.utools.club/p/order/payNotify");
        //创建预订单
        AlipayF2FPrecreateResult result = alipayTradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()){
            case SUCCESS:
                //下预订单成功
                AlipayTradePrecreateResponse response = result.getResponse();
                String qrCode = response.getQrCode();
                System.out.println(qrCode);
                return qrCode;
            case FAILED:
                log.error("创建预订单失败，订单号为{}" + orderNumber);
                throw new RuntimeException("创建预订单失败");
            case UNKNOWN:
                log.error("创建预订单失败,订单号为{}" + orderNumber);
            default:
                return "失败";
        }
    }

    /**
     * 支付宝的验签
     *
     * @param map
     * @return
     */
    @Override
    public Boolean resCheck(Map<String, String> map) {
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(map, aliProperties.getAliPublicKey(), "UTF-8", aliProperties.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改订单状态 已经支付
     *
     * @param orderNum
     */
    @Override
    public void changeOrderStatus(String orderNum) {
        payOrderFeign.changeOrderStatus(orderNum);
    }

    /**
     * 查询ali那边是否成功
     *
     * @param orderNum
     * @return
     */
    @Override
    public Boolean queryAliOrderPay(String orderNum) {
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder();
        builder.setOutTradeNo(orderNum);
        //根据商户订单号 查询是否支付成功
        AlipayF2FQueryResult queryResult = alipayTradeService.queryTradeResult(builder);
        return queryResult.isTradeSuccess();
    }

}
